import api from '../../api/api'
import {cartallselected, getShoppingcart, toCheckout, removecartitem, updatecartitem} from '../../api/conf'

Page({
  data: {
    cartGoodsList: [],
    orderTotal: '0.00',
    isAllSelected: false,
    isDisabled: true
  },
  onLoad: function () {

  },
  onShow: function () {
    this.getTabBar().init();
    this.getShoppingCart()
  },

  getShoppingCart: function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    let isDisabled = true
    api.get(getShoppingcart).then(res => {
      const cartGoodsList = res.Data.Items
      for(let i=0;i < cartGoodsList.length; i++){
        if(cartGoodsList[i].Selected){
          isDisabled = false
          break
        }
      }
      this.setData({
        cartGoodsList,
        isDisabled,
        orderTotal: res.Data.OrderTotal
      })
      wx.hideLoading()
      wx.hideNavigationBarLoading()
    })
  },

  onGoodsSelect: function (e){
    const {goods} = e.detail
    this.updateCartItem(goods.Id, goods.Qty, !goods.Selected)
  },

  onQuantityChange: function (e) {
    const {goods} = e.detail
    const {quantity} = e.detail
    this.updateCartItem(goods.Id, quantity, goods.Selected)
  },

  updateCartItem: function (id, quantity, selected) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    api.post(updatecartitem, {
      Id: id,
      Quantity: quantity,
      Selected: selected
    }).then(res => {
      this.getShoppingCart()
    })
  },

  onSelectAll: function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    const {isAllSelected} = this.data
    api.post(cartallselected + '?selected=' + !isAllSelected).then(res => {
      this.setData({
        isAllSelected: !isAllSelected
      })
      this.getShoppingCart()
    })
  },

  onGoodsDelete: function (e) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    const {goods} = e.detail
    api.post(
      removecartitem + "?id=" + goods.Id,
      {}
    ).then(res => {
      this.getShoppingCart()
    })
  },
  onToSettle: function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    api.post(
      toCheckout, {}
    ).then(res => {
      wx.navigateTo({
        url: '/pages/checkout/checkout'
      })
    })
  },
  onGotoHome: function () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})